package com.goodfather.textbook.youdao.pad.ui;

import android.animation.FloatEvaluator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.goodfather.textbook.youdao.pad.R;
import com.goodfather.textbook.youdao.pad.bean.BookDetail;
import com.goodfather.textbook.youdao.pad.bean.Lessons;
import com.goodfather.textbook.youdao.pad.bean.Pages;
import com.goodfather.textbook.youdao.pad.bean.ProductionDetail;
import com.goodfather.textbook.youdao.pad.bean.Sentence;
import com.goodfather.textbook.youdao.pad.bean.UserData;
import com.goodfather.textbook.youdao.pad.bean.UserManager;
import com.goodfather.textbook.youdao.pad.pac.BookCatalogAdapter;
import com.goodfather.textbook.youdao.pad.pac.BookPresenter;
import com.goodfather.textbook.youdao.pad.pac.Constants;
import com.goodfather.textbook.youdao.pad.pac.IBookView;
import com.goodfather.textbook.youdao.pad.pac.PageFlipAdapter;
import com.goodfather.textbook.youdao.pad.util.C;
import com.goodfather.textbook.youdao.pad.util.L;
import com.goodfather.textbook.youdao.pad.util.MediaPlayerService;
import com.goodfather.textbook.youdao.pad.util.NetworkUtils;
import com.goodfather.textbook.youdao.pad.util.PageImgHelper;
import com.goodfather.textbook.youdao.pad.util.PayDialog;
import com.goodfather.textbook.youdao.pad.util.StringUtil;
import com.goodfather.textbook.youdao.pad.util.ThreadUtil;
import com.goodfather.textbook.youdao.pad.util.ToastUtil;
import com.goodfather.textbook.youdao.pad.weight.AudioImageView;
import com.goodfather.textbook.youdao.pad.weight.AudioSentenceView;
import com.goodfather.textbook.youdao.pad.weight.PageWidget;
import com.goodfather.textbook.youdao.pad.weight.ToolbarActivity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * @Description:
 * @Author: zhou
 * @CreateDate: 2021/10/13
 */
public class BookDetailActivity extends ToolbarActivity implements BookCatalogAdapter.ItemClickListener, PageWidget.OnPageChangeListener, View.OnClickListener, IBookView {

    ImageView iv_go_left;
    ImageView iv_go_right;
    ImageView ivLeft;
    PageWidget mPageWidget;
    AudioImageView ivFirst;
    FrameLayout flFirst;
    AudioImageView ivSecond;
    FrameLayout flSecond;
    ImageView ivRight;
    TextView tvCnText;
    ImageView ivBack;
    RelativeLayout rlCatalog;
    ImageView ivCatalog;
    RecyclerView rvCatalog;
    ImageView ivPlayOrPause;
    ImageView ivSetting;
    RelativeLayout rlParent;
    RelativeLayout rlMenu;
    RelativeLayout rlTranslate;
    RadioGroup rgFlip;
    RadioButton rbAuto;
    RadioButton rbManual;
    RadioGroup rgChinese;
    RadioButton rbOpen;
    RadioButton rbClose;
    ImageView ivUnlockTape;
    RelativeLayout rlUnlockTape;
    private boolean mIsBound;
    private BookPresenter bookPresenter;
    private String bookId;
    private String publishingId;
    private String subjectId;
    private String lessonId;
    private String providerClickMode;
    private String providerUserID;//有道用户Id
    private ValueAnimator valueAnimator = new ValueAnimator().ofFloat(0, 1).setDuration(150);
    private ArrayList<Lessons> allLessons;
    private PageFlipAdapter mPageAdapter;
    private ArrayList<Pages> allPages;
    private SparseArray<View> touchAreas = new SparseArray<>();
    private int mLeftIndex = 0;
    private int mRightIndex = 1;
    private int mCurPlayLessonIndex = 0;
    private float defaultMultiple = 1.4f;//点读区域放大的默认倍数
    private float multipleX = defaultMultiple;//点读区域X放大的倍数
    private float multipleY = defaultMultiple;//点读区域Y放大的倍数
    private int duration = 200;//点读区域放大（还原）持续时间
    private boolean leftFinish, rightFinish;  // 左、右页图加载完成标记
    private float ratio_w, ratio_h;  // 宽高比
    private boolean startFromLeft = true;  // 是否从左页开始播放
    private Bitmap mLBitmap, mRBitmap, mBitmap;
    private BookHandler mBookHandler;
    private ArrayList<Sentence> allSentences;
    private Sentence currentSentence;
    private boolean isPlaying = true;
    private BookDetail mBookDetail;
    private boolean playIsAuto = true;//当前播放状态是自动
    private boolean translateIsOpen = true;//当前翻译是开
    private int mPayStartIndex;  // 需开始支付的页面下标
    private int mSelectIndex; // 选中lesson下标
    private final int KEY_TAG_TO_PAUSE = R.id.key_tag_to_pause;
    private BookCatalogAdapter mCatalogAdapter;
    private boolean AudioLoadFinish;
    private boolean mPurchased;
    private ProductionDetail mProductionDetail;
    private Runnable mChangeRunable;
    private PayDialog mBuyDialog;
    //huaweipay
    private String productId;
    private String TAG = "HUAWEIEDU";

    /**
     * deal image load result
     */
    private static class BookHandler extends Handler {
        private final WeakReference<Activity> mWeakReference;

        private BookHandler(Activity activity) {
            mWeakReference = new WeakReference<Activity>(activity);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_book_details;
    }


    @Override
    protected void parseIntent() {
        super.parseIntent();
        Bundle bundle = mIntent.getExtras();
        if (bundle != null) {
            providerClickMode = bundle.getString("providerClickMode", "1");
            bookId = bundle.getString("bookId");
            publishingId = bundle.getString("publishingId");
            subjectId = bundle.getString("subjectId");
            lessonId = bundle.getString("lessonId");
        }
    }


    @Override
    protected void initViews() {
        iv_go_left = findViewById(R.id.iv_go_left);
        iv_go_right = findViewById(R.id.iv_go_right);
        ivLeft = findViewById(R.id.iv_left);
        ivRight = findViewById(R.id.iv_right);
        mPageWidget = findViewById(R.id.page_widget);
        ivFirst = findViewById(R.id.iv_first);
        flFirst = findViewById(R.id.fl_first);
        ivSecond = findViewById(R.id.iv_second);
        ivSetting = findViewById(R.id.iv_setting);
        flSecond = findViewById(R.id.fl_second);
        tvCnText = findViewById(R.id.tv_cnText);
        ivBack = findViewById(R.id.iv_back);
        rlCatalog = findViewById(R.id.rl_catalog);
        ivCatalog = findViewById(R.id.iv_catalog);
        rvCatalog = findViewById(R.id.rv_catalog);
        ivPlayOrPause = findViewById(R.id.iv_play_or_pause);
        rlParent = findViewById(R.id.rl_parent);
        rlMenu = findViewById(R.id.rl_menu);
        rlTranslate = findViewById(R.id.rl_translate);
        rgFlip = findViewById(R.id.rg_flip);
        rbAuto = findViewById(R.id.rb_auto);
        rbManual = findViewById(R.id.rb_manual);
        rgChinese = findViewById(R.id.rg_chinese);
        rbOpen = findViewById(R.id.rb_open);
        rbClose = findViewById(R.id.rb_close);
        ivUnlockTape = findViewById(R.id.iv_unlock_tape);
        rlUnlockTape = findViewById(R.id.rl_unlock_tape);
        ivBack.setOnClickListener(this);
        ivCatalog.setOnClickListener(this);
        ivPlayOrPause.setOnClickListener(this);
        ivSetting.setOnClickListener(this);
        iv_go_left.setOnClickListener(this);
        iv_go_right.setOnClickListener(this);
        ivUnlockTape.setOnClickListener(this);
        //
        rvCatalog.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        mCatalogAdapter = new BookCatalogAdapter(this, null);
        mCatalogAdapter.setOnItemClickListener(this);
        rvCatalog.setAdapter(mCatalogAdapter);
        if ("EN".equalsIgnoreCase(subjectId)) {
            isMenuCnShow(false);
        } else {
            isMenuCnShow(true);
        }
        Intent intentService = new Intent(this, MediaPlayerService.class);
        intentService.putExtra(MediaPlayerService.BOOK_ID, bookId);
        intentService.putExtra(MediaPlayerService.PUBLISHING_ID, publishingId);
        startService(intentService);
        doBindService();
        mPageWidget.setOnPageChangeListener(this);
        initRb();
    }

    @Override
    protected void initData() {
        translateIsOpen = C.getPreference(Constants.KEY_CHINESE_TRANSLATE_SWITCH, true);
        playIsAuto = C.getPreference(Constants.KEY_PAGE_FLIP_MODEL, true);
        bookPresenter = new BookPresenter(this);
        bookPresenter.getBookDetail(bookId, publishingId);
    }

    /**
     * handler of incoming messages from service
     */
    private static class IncomingHandler extends Handler {
        private final WeakReference<Activity> mReference;

        public IncomingHandler(Activity activity) {
            mReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (mReference.get() == null || !(mReference.get() instanceof BookDetailActivity)) {
                return;
            }
            BookDetailActivity activity = (BookDetailActivity) mReference.get();
            switch (msg.what) {
                case MediaPlayerService.MSG_ON_SENTENCE_PLAY_BEGIN:
                    if (msg.obj instanceof Sentence) {
                        Sentence sentence = (Sentence) msg.obj;
                        activity.onSentenceBegin(sentence);
                    }
                    break;

                case MediaPlayerService.MSG_ON_SENTENCE_PLAY_END:
                    if (msg.obj instanceof Sentence) {
                        Sentence sentence = (Sentence) msg.obj;
                        activity.onSentenceEnd(sentence);
                    }
                    break;

                case MediaPlayerService.MSG_ON_SENTENCE_CANCEL:
                    if (msg.obj instanceof Sentence) {
                        Sentence sentence = (Sentence) msg.obj;
                        activity.clearReadingAreaHint(sentence.sentenceId);
                    }
                    break;
                case MediaPlayerService.MSG_ON_DURATION:
                    int duration = (int) msg.obj;
                    activity.loadAudioFinish(true);
                    activity.duration = duration;
                    break;
                case MediaPlayerService.MSG_ON_AUDIO_ID:
                    String lessonId = (String) msg.obj;
                    activity.getLessonIndex(lessonId);
                    break;
                case MediaPlayerService.MSG_ON_AUDIO_ERROR:
                    ToastUtil.showLongToast("正在加载中...请点击重试");
//                    ToastUtil.showShortToast("音频加载异常");
                    break;
                case MediaPlayerService.MSG_ON_AUDIO_PREPARE:
                    boolean finish = (boolean) msg.obj;
                    activity.loadAudioFinish(finish);
                    break;
                case MediaPlayerService.MSG_ON_PLAYER_PAUSE:
                    activity.showPlayOrPause(false);
                    break;

                default:
                    super.handleMessage(msg);
            }
            super.handleMessage(msg);
        }
    }

    private void loadAudioFinish(boolean finish) {
        AudioLoadFinish = finish;
    }

    /**
     * 获取当前lesson position
     *
     * @param lessonId
     */
    private void getLessonIndex(String lessonId) {
        if (allLessons == null) return;
        for (int i = 0; i < allLessons.size(); i++) {
            if (allLessons.get(i).lessonId.equals(lessonId)) {
                mCurPlayLessonIndex = i;
                mSelectIndex = mCurPlayLessonIndex;
                if (mCatalogAdapter != null) {
                    mCatalogAdapter.setCurPosition(mCurPlayLessonIndex);
                }
            }
        }
    }

    /**
     * 句子播放结束
     *
     * @param sentence
     */
    private void onSentenceEnd(Sentence sentence) {

        clearReadingAreaHint(sentence.sentenceId);
        // 判断结束时是否操作过翻页
        if ((flFirst != null && flFirst.getTag() != null && sentence.pageNo == (int) flFirst.getTag())
                || (flSecond != null && flSecond.getTag() != null && sentence.pageNo == (int) flSecond.getTag())) {
            readNextSentenceAllLesson(sentence);
        }
    }

    /**
     * 读下一个句子
     *
     * @param lastSentence
     */
    private void readNextSentenceAllLesson(Sentence lastSentence) {
        if (allSentences != null && !allSentences.isEmpty()) {
            int index = allSentences.indexOf(lastSentence);
            if (index != -1) {
                if (index + 1 < allSentences.size()) {
                    readSentence(allSentences.get(index + 1));
                }
            }
        }
    }

    /**
     * 播放句子
     *
     * @param sentence
     */
    public void readSentence(Sentence sentence) {
        L.d("播放句子---" + sentence.audioUrl);
        if (!NetworkUtils.isNetworkAvailable(C.get())) {
            ToastUtil.showShortToast("请连接网络哦");
            return;
        }
        if (sentence == null || StringUtil.isEmpty(sentence.audioUrl)) {
            ToastUtil.showShortToast("当前句子无内容");
            return;
        }
        if (currentSentence == null) {
            currentSentence = sentence;
        } else {
            clearReadingAreaHint(currentSentence.sentenceId);
            currentSentence = sentence;
        }
        /**
         * 播放句子时翻到句子所在页，同时判断该页是否免费
         *
         */
        boolean isFree = false;
        if (rlUnlockTape != null && rlUnlockTape.getVisibility() == View.VISIBLE) {
            isFree = turnPageOfSentence2(sentence);
        } else {
            isFree = turnPageOfSentence(sentence);
        }
        if (isFree) {
            sentence.endTime = computeEndTime(sentence);
            showPlayOrPause(true);
            onSentenceBegin(sentence);
            sendMessageToService(MediaPlayerService.MSG_PLAY_SENTENCE, sentence);
        }
    }

    /**
     * 计算句子结束时间
     *
     * @param sentence
     * @return
     */
    private String computeEndTime(Sentence sentence) {
        if (sentence.endTime != null && !sentence.endTime.isEmpty()) {
            return sentence.endTime;
        } else {
            String endTime = "";
            if (allSentences != null && !allSentences.isEmpty()) {
                int index = allSentences.indexOf(sentence);
                if (index != -1) {
                    if (index + 1 < allSentences.size()) {
                        endTime = allSentences.get(index + 1).beginTime;
                    } else {//最后一句
                        endTime = "0";
                    }
                }
            }

            return endTime;
        }
    }

    /**
     * 开始或暂停播放
     *
     * @param isPlay
     */
    private void playOrPauseSentence(boolean isPlay) {
        if (!isPlay) {
            cancelSentence();
        } else {
            if (currentSentence == null) {
                //翻页后，则播放当前页第一个句子
                Sentence sentence = null;
                if (startFromLeft) {
                    if (mLeftIndex < allPages.size() && allPages.get(mLeftIndex).sentences != null
                            && allPages.get(mLeftIndex).sentences.size() > 0) {
                        sentence = allPages.get(mLeftIndex).sentences.get(0);
                    } else {
                        if (mRightIndex < allPages.size() && allPages.get(mRightIndex).sentences != null
                                && allPages.get(mRightIndex).sentences.size() > 0) {  // 左页没句子
                            sentence = allPages.get(mRightIndex).sentences.get(0);
                        } else {  //左右都没句子
                            cancelSentence();
                            if (mRightIndex >= allPages.size()) return;
                            if (!playIsAuto) {
                                ToastUtil.showShortToast("这一页不会发音哦");
                                return;
                            }
                            showAnim(true);
                            return;
                        }
                    }
                } else {
                    startFromLeft = true;
                    if (mRightIndex < allPages.size() && allPages.get(mRightIndex).sentences != null
                            && allPages.get(mRightIndex).sentences.size() > 0) {
                        sentence = allPages.get(mRightIndex).sentences.get(0);
                    } else {  // 右页没句子
                        cancelSentence();
                        if (mRightIndex >= allPages.size()) return;
                        if (!playIsAuto) {
                            ToastUtil.showShortToast("这一页不会发音哦");
                            return;
                        }
                        showAnim(true);
                        return;
                    }

                }

                readSentence(sentence);

            } else {
                readSentence(currentSentence);
            }

        }
    }

    private void pauseAudio() {
        sendMessageToService(MediaPlayerService.MSG_PLAYER_PAUSE, null);
    }

    /**
     * 句子恢复原状
     */
    public void cancelSentence() {
        if (currentSentence != null) {
            clearReadingAreaHint(currentSentence.sentenceId);
        }
        sendMessageToService(MediaPlayerService.MSG_CANCEL_SENTENCE, null);
    }

    private void sendMessageToService(int type, Object obj) {
        if (mIsBound) {
            if (mService != null) {
                try {
                    Message msg = Message.obtain(null, type);
                    if (obj != null) {
                        msg.obj = obj;
                    }
                    msg.replyTo = mClientMessenger;
                    mService.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private Messenger mClientMessenger = new Messenger(new IncomingHandler(this));

    private Messenger mService;
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = new Messenger(service);
            try {
                Message message = Message.obtain(null, MediaPlayerService.MSG_REGISTER_CLIENT);
                message.replyTo = mClientMessenger;
                mService.send(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }
    };

    void doBindService() {
        Intent intent = new Intent(this, MediaPlayerService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }

    void doUnbindService() {
        if (!mIsBound || mService == null) return;
        try {
            Message message = Message.obtain(null, MediaPlayerService.MSG_UNREGISTER_CLIENT);
            message.replyTo = mClientMessenger;
            mService.send(message);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        unbindService(mConnection);
        mIsBound = false;
    }

    private void initRb() {
        playIsAuto = C.getPreference(Constants.KEY_PAGE_FLIP_MODEL, true);
        translateIsOpen = C.getPreference(Constants.KEY_CHINESE_TRANSLATE_SWITCH, true);

        rgFlip.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (R.id.rb_auto == checkedId) {
                    C.setPreference(Constants.KEY_PAGE_FLIP_MODEL, true);
                } else {
                    C.setPreference(Constants.KEY_PAGE_FLIP_MODEL, false);
                }
                playIsAuto = C.getPreference(Constants.KEY_PAGE_FLIP_MODEL, true);
            }
        });

        rgChinese.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (R.id.rb_open == checkedId) {
                    C.setPreference(Constants.KEY_CHINESE_TRANSLATE_SWITCH, true);
                } else {
                    C.setPreference(Constants.KEY_CHINESE_TRANSLATE_SWITCH, false);
                }
                showTranslation();
            }
        });

        if (playIsAuto) {
            rbAuto.setChecked(true);
        } else {
            rbManual.setChecked(true);
        }
        if (translateIsOpen) {
            rbOpen.setChecked(true);
        } else {
            rbClose.setChecked(true);
        }
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void showBookDetail(BookDetail detail) {
        L.d("书本数据==" + JSONObject.toJSONString(detail));
        if (detail == null || detail.lessons == null || detail.lessons.size() == 0 ||
                detail.pages == null || detail.pages.size() == 0) {
            ToastUtil.showShortToast(getString(R.string.no_detail));
            return;
        }
        mBookDetail = detail;
        getProduction(false);
    }

    /**
     * 获取书本商品信息，检查是否购买过
     */
    private void getProduction(boolean afterLogin) {
        if (bookPresenter != null) {
            bookPresenter.getProductionDetail(mBookDetail.productionId + "", afterLogin);
        }
    }

    @Override
    public void showProduction(ProductionDetail productionDetail, boolean afterLogin) {
        if (productionDetail == null) return;
        mProductionDetail = productionDetail;
        mPurchased = productionDetail.getRecover().isPurchased();
        if (mPurchased) {
            showUnlockTape(false);
        }
        filterLessons(mBookDetail);
        filterPages(mBookDetail);
        setLessonIndex();
        setLessonEndPageNo();
        setPageRealNum();
        showPages();
        showFrameImg();
        showTeachCatalog(allLessons);
        sortSentences();
        changeLessonFromEdu();//启动时跳转:需要修改逻辑
    }

    /**
     * 设置单元结束页码
     */
    private void setLessonEndPageNo() {
        for (int i = 0; i < allLessons.size(); i++) {
            if (i < allLessons.size() - 1) {
                if (allLessons.get(i).beginPageNum == allLessons.get(i + 1).beginPageNum) {
                    allLessons.get(i).endPageNum = allLessons.get(i + 1).beginPageNum;
                } else {
                    allLessons.get(i).endPageNum = allLessons.get(i + 1).beginPageNum - 1;
                }

            } else {
                allLessons.get(i).endPageNum = allLessons.get(i).beginPageNum + allLessons.get(i).pages.size() - 1;
            }
        }
    }

    /**
     * 设置page 真实页码
     */
    private void setPageRealNum() {
        for (Lessons lesson : allLessons) {
            int beginPageNum = lesson.beginPageNum;
            int endPageNum = lesson.endPageNum;
            if (lesson.pages == null || lesson.pages.size() == 0) return;
            Pages pages = lesson.pages.get(0);
            int pageNumOffset = beginPageNum - pages.pageNo;
            // 该方法可能走多次,只执行一次
            for (Pages page : lesson.pages) {
                if (page.pageNum > 0) continue;
                page.pageNum = page.pageNo + pageNumOffset;
            }
        }
    }

    /**
     * 中文不显示翻译（不显示中文提示）
     */
    private void isMenuCnShow(boolean isCn) {
        if (isCn) {
            rlTranslate.setVisibility(View.GONE);
            tvCnText.setVisibility(View.GONE);
        } else {
            rlTranslate.setVisibility(View.VISIBLE);
            showTranslation();
        }
    }

    /**
     * 显示翻译
     */
    public void showTranslation() {
        translateIsOpen = C.getPreference(Constants.KEY_CHINESE_TRANSLATE_SWITCH, true);
        if (translateIsOpen) {
            tvCnText.setVisibility(View.VISIBLE);
        } else {
            tvCnText.setVisibility(View.GONE);
        }
    }

    /**
     * 过滤测试章节
     *
     * @param detail
     */
    private void filterLessons(BookDetail detail) {
        allLessons = new ArrayList<>();
        for (Lessons lesson : detail.lessons) {
            if (lesson.kindId == 1) {
                allLessons.add(lesson);
            }
        }
    }

    /**
     * 过滤没有坐标的句子
     *
     * @param detail
     */
    private void filterPages(BookDetail detail) {
        ArrayList<Pages> mPages = new ArrayList<>();
        for (Pages page : detail.pages) {
            if (TextUtils.isEmpty(page.lessonId)) continue;
            List<Sentence> sentenceList = page.sentences;
            if (sentenceList == null || sentenceList.size() == 0) {
                mPages.add(page);
                continue;
            }
            List<Sentence> sentences = new ArrayList<>();
            for (Sentence sentence : sentenceList) {
                //屏蔽坐标为（0，0，0，0）或者没有坐标 的句子,且beginTime 不能为空
                if (!TextUtils.isEmpty(sentence.startX) &&
                        !TextUtils.isEmpty(sentence.startY) &&
                        !TextUtils.isEmpty(sentence.endX) &&
                        !TextUtils.isEmpty(sentence.endY) &&
                        !"0".equals(sentence.startX) &&
                        !"0".equals(sentence.startY) &&
                        !"0".equals(sentence.endX) &&
                        !"0".equals(sentence.endY)
                        && !TextUtils.isEmpty(sentence.beginTime)) {

                    float startX = 0;
                    float startY = 0;
                    float endX = 0;
                    float endY = 0;
                    try {
                        startX = Float.valueOf(sentence.startX);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                    try {
                        startY = Float.valueOf(sentence.startY);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                    try {
                        endX = Float.valueOf(sentence.endX);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                    try {
                        endY = Float.valueOf(sentence.endY);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }

                    if (startX > 0 && startY > 0 && endX > 0 && endY > 0) {
                        sentences.add(sentence);
                    }
                }
            }
            if (sentences.size() > 0) {
                Collections.sort(sentences);
            }
            page.sentences = sentences;
            mPages.add(page);
        }

        for (Lessons lesson : allLessons) {
            lesson.pages = new ArrayList<>();
            for (Pages page : mPages) {
                if (lesson.lessonId.equalsIgnoreCase(page.lessonId) && page.pageNo >= lesson.beginPage) {
                    lesson.pages.add(page);
                }
            }
        }

    }

    /**
     * 章节句子排序
     */
    private void sortSentences() {
        allSentences = new ArrayList<>();
        for (Lessons lesson : allLessons) {
            ArrayList<Sentence> sentences = new ArrayList();
            for (int i = 0; i < lesson.pages.size(); i++) {
                List<Sentence> sentencesList = lesson.pages.get(i).sentences;
                if (sentencesList != null && sentencesList.size() > 0)
                    sentences.addAll(sentencesList);
            }
            Collections.sort(sentences);
            lesson.sentences = sentences;
            allSentences.addAll(sentences);
        }
    }

    /**
     * 绘制翻页背景，设置页码
     */
    private void showPages() {
        if (allPages == null) {
            allPages = new ArrayList<>();
        }
        allPages.clear();
        if (allLessons == null || allLessons.size() == 0) return;
        for (int i = 0; i < allLessons.size(); i++) {
            allPages.addAll(allLessons.get(i).pages);
        }
        // 设置页码
        for (int i = 0; i < allPages.size(); i++) {
            allPages.get(i).index = i;
        }
        mPageAdapter = new PageFlipAdapter(this, allPages);
        mPageWidget.setAdapter(mPageAdapter);
    }

    /**
     * 设置章节下标
     */
    private void setLessonIndex() {
        if (allLessons == null || allLessons.size() == 0 || mPageWidget == null) return;
        for (int i = 0; i < allLessons.size(); i++) {
            int count = allLessons.get(i).pages.size();
            if (i == 0) {
                allLessons.get(i).startIndex = 0;
                allLessons.get(i).endIndex = count - 1;
            } else {
                allLessons.get(i).startIndex = allLessons.get(i - 1).endIndex + 1;
                allLessons.get(i).endIndex = allLessons.get(i).startIndex + count - 1;
            }
        }
        if (mBookDetail.freeLessons > allLessons.size()) {
            ToastUtil.show("数据异常");
        } else {
            mPayStartIndex = allLessons.get(mBookDetail.freeLessons).startIndex;
            mPageWidget.setPayPageIndex(mPayStartIndex);
            if (mPurchased) {
                mPageWidget.setFlipAllPage(true);
            } else {
                if (getLockState()) {
                    mPageWidget.setFlipAllPage(true);
                } else {
                    mPageWidget.setFlipAllPage(false);
                }

            }
        }
    }

    /**
     * 设置目录列表
     */
    private void showTeachCatalog(List<Lessons> lessons) {
        if (mPurchased || directUnlock()) {
            mCatalogAdapter.setPurchased(true);
        }
        mCatalogAdapter.setData(lessons);
    }

    /**
     * 显示书籍样式
     */
    void showFrameImg() {
        if (ivLeft == null || ivRight == null) return;
        ivLeft.setVisibility(View.VISIBLE);
        ivRight.setVisibility(View.VISIBLE);
    }


    /**
     * 启动时默认章节切换
     */
    private void changeDefaultLesson() {
        if (mLeftIndex > -1) {
            if (mProductionDetail.getRecover().isPurchased()) {
                changeLesson(mLeftIndex, mLeftIndex + 1);
            } else {
                mCurPlayLessonIndex = 0;
                changeLessons(allLessons.get(0));
            }
        }
    }

    /**
     * 华为教育中心拉起指定页跳转
     */
    public void changeLessonFromEdu() {
        if (allLessons != null) {
            for (Lessons lesson : allLessons) {
                if (lessonId.equalsIgnoreCase(lesson.lessonId)) {
                    changeLessons(lesson);
                    break;
                }
            }
        } else {
            changeDefaultLesson();
        }
    }


    /**
     * 切换课程
     *
     * @param lesson
     */
    private void changeLessons(Lessons lesson) {
        if (lesson.startIndex % 2 == 0) { // 开始页是偶数，正常翻页，从左边开始播放
            startFromLeft = true;
            changeLesson(lesson.startIndex, lesson.startIndex + 1);
        } else {  //开始页是奇数，从右边开始播放
            changeLesson(lesson.startIndex - 1, lesson.startIndex);
            startFromLeft = false;
        }
    }

    /**
     * 切换课程
     */
    private void changeLesson(int leftIndex, int rightIndex) {
        if (mPageWidget == null) return;
        int index = (int) Math.ceil(leftIndex / 2);
        if (index > mPageAdapter.getCount()) { // 防止越界
            index = mPageAdapter.getCount();
        }
        mPageWidget.resetAdapter(index, mPageAdapter);
        mLeftIndex = leftIndex;
        mRightIndex = rightIndex;
        currentSentence = null;
        //翻页的页数
        mPageWidget.setCurPosition(index);
        changePages(mLeftIndex, mRightIndex);
    }


    @Override
    public void onPageScrolled(int position) {
        if (currentSentence != null) {
            clearReadingAreaHint(currentSentence.sentenceId);
        }
        cancelSentence();
//        computeDuerStage("mid", mLeftIndex);
        mLeftIndex = position * 2;
        mRightIndex = position * 2 + 1;

        if (mChangeRunable != null) {
            ThreadUtil.getMainHandler().removeCallbacks(mChangeRunable);
        }
        //延迟 1 秒改变页
        mChangeRunable = new Runnable() {
            @Override
            public void run() {
                changePages(mLeftIndex, mRightIndex);
            }
        };
        ThreadUtil.getMainHandler().postDelayed(mChangeRunable, 500);
    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageStateChange(int position) {
        playOrPauseSentence(false); // 暂停播放
        pauseAudio();
        showPayDialog(true);
    }

    /**
     * 手动翻页
     *
     * @param isRight
     */
    private void flipPage(boolean isRight) {
//        if (isFastClick()) {
//            return;
//        }
        if (isRight) {
            if (!mPurchased && mRightIndex + 1 >= mPayStartIndex) {
                showPlayOrPause(false);
                playOrPauseSentence(false); // 暂停播放
                boolean supportUnlock = getLockState();
                if (supportUnlock) {
                    showUnlockTape(true);
                } else {
                    showPayDialog(true);
//                    computeDuerStage("mid", mLeftIndex);
                    return;
                }
            }
            if (allPages != null && mRightIndex + 1 > allPages.size() - 1) {
                ToastUtil.showShortToast(getString(R.string.read_completed));
                return;
            }
            if (currentSentence != null)
                clearReadingAreaHint(currentSentence.sentenceId);
            currentSentence = null;
            showAnim(true);

        } else {
            if (mLeftIndex - 1 < 0) {
                ToastUtil.showShortToast(getString(R.string.the_curpage_is_first));
                return;
            }
            if (!mPurchased && mLeftIndex - 1 >= mPayStartIndex) {
                showPlayOrPause(false);
                playOrPauseSentence(false); // 暂停播放
                boolean supportUnlock = getLockState();
                if (supportUnlock) {
                    showUnlockTape(true);
                } else {
                    showPayDialog(true);
//                    computeDuerStage("mid", mLeftIndex);
                    return;
                }
            }
            if (currentSentence != null)
                clearReadingAreaHint(currentSentence.sentenceId);
            cancelSentence();
            currentSentence = null;
            showAnim(false);
        }
    }

    private void showAnim(boolean isRight) {
        cancelSentence();
        showPlayOrPause(false);
        ;
        if (mPageWidget == null) return;
        float leftStartY, rightStartY, leftEndY, rightEndY;
        int leftStartX = mPageWidget.getLeft();
        int rightStartX = mPageWidget.getWidth();
        leftStartY = rightStartY = mPageWidget.getHeight();
        //分割线左侧
        float leftEndX = mPageWidget.getWidth() / 2.0f - 10;
        //分割线右侧
        float rightEndX = mPageWidget.getWidth() / 2.0f + 10;
        leftEndY = rightEndY = rightStartY - 150;
//        if (mPageWidget.isAnimated()) return;
        if (isRight) {
            startAnim(rightStartX, rightEndX, rightStartY, rightEndY);
        } else {
            startAnim(leftStartX, leftEndX, leftStartY, leftEndY);
        }
    }

    private void startAnim(final float startX, final float endX, final float startY, final float endY) {
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float animatedFraction = animation.getAnimatedFraction();
                Float evaluate = new FloatEvaluator().evaluate(animatedFraction, startX, endX);
                Float evaluate2 = new FloatEvaluator().evaluate(animatedFraction, startY, endY);
                if (mPageWidget != null) {
                    mPageWidget.flipDown(evaluate, evaluate2);
                }
            }
        });
        valueAnimator.start();
    }

    /**
     * 翻到指定的页
     *
     * @param leftIndex
     */
    private void changePages(int leftIndex, int rightIndex) {
        if (leftIndex < 0) {
            return;
        }

        if (ivFirst == null || ivSecond == null) return;
        mLBitmap = null;
        mRBitmap = null;
        if (ivFirst != null) {
            ivFirst.setImageBitmap(null);
            ivFirst.setVisibility(View.VISIBLE);
        }

        if (ivSecond != null) {
            ivSecond.setVisibility(View.VISIBLE);
            ivSecond.setImageBitmap(null);
        }
        currentSentence = null;
        mLeftIndex = leftIndex;
        mRightIndex = rightIndex;
        leftFinish = false;
        rightFinish = false;
        if (mBookHandler != null) {
            mBookHandler.removeCallbacksAndMessages(null);
        }
        changeLearningLesson(mLeftIndex, mRightIndex);

        boolean isFree1 = checkSentenceFree(allPages.get(mLeftIndex).pageNo);
        if (!isFree1 && getLockState()) {
            showUnlockTape(true);
        } else {
            showUnlockTape(false);
        }
        if (rightIndex < allPages.size()) {
            boolean isFree2 = checkSentenceFree(allPages.get(mRightIndex).pageNo);
            if (!isFree2 && getLockState()) {
                showUnlockTape(true);
            } else {
                showUnlockTape(false);
            }
        }

        PageImgHelper.loadImage(allPages.get(leftIndex).pageNo, allPages.get(leftIndex).imageUrl, ivFirst, flFirst, new PageImgHelper.ImageRatioCallBack() {
            @Override
            public void imageRatio(float wRatio, float hRatio) {
                leftFinish = true;
                if (wRatio > 0)
                    ratio_w = wRatio;
                if (hRatio > 0) {
                    ratio_h = hRatio;
                }
                if (ivFirst != null)
                    ivFirst.setVisibility(View.GONE);
            }
        });
        if (rightIndex >= allPages.size()) {
            renderTouchAreaLeft();
            if (ivSecond != null)
                ivSecond.setVisibility(View.GONE);
            return; //size 为奇数，右边没有页
        }
        PageImgHelper.loadImage(allPages.get(rightIndex).pageNo, allPages.get(rightIndex).imageUrl, ivSecond, flSecond, new PageImgHelper.ImageRatioCallBack() {
            @Override
            public void imageRatio(float wRatio, float hRatio) {
                rightFinish = true;
                if (wRatio > 0)
                    ratio_w = wRatio;
                if (hRatio > 0) {
                    ratio_h = hRatio;
                }
                if (ivSecond != null)
                    ivSecond.setVisibility(View.GONE);
            }
        });
        renderTouchArea();
    }

    /**
     * 设置当前学习的 lesson
     *
     * @param left
     * @param right
     */
    private void changeLearningLesson(int left, int right) {
        String leftLessonId = null, rightLessonId = null;
        if (left < allPages.size()) {
            leftLessonId = allPages.get(left).lessonId;
        }
        if (right < allPages.size()) {
            rightLessonId = allPages.get(right).lessonId;
        }
        if (TextUtils.isEmpty(leftLessonId) && TextUtils.isEmpty(rightLessonId)) return;
        if (!TextUtils.isEmpty(leftLessonId) && TextUtils.isEmpty(rightLessonId)) {
            getLessonIndex(leftLessonId);
            return;
        }
        if (!TextUtils.isEmpty(leftLessonId) && !TextUtils.isEmpty(rightLessonId)) {
            getLessonIndex(rightLessonId);
            return;
        }
        if (TextUtils.isEmpty(leftLessonId) && !TextUtils.isEmpty(rightLessonId)) {
            getLessonIndex(rightLessonId);
            return;
        }
    }

    /**
     * 暂停/开始播放
     *
     * @param isPlay
     */
    private void showPlayOrPause(boolean isPlay) {
        if (ivPlayOrPause != null) {
            if (isPlay) {
//                ivPlayOrPause.setTag(KEY_TAG_TO_PAUSE, true);
                isPlaying = true;
                ivPlayOrPause.setImageResource(R.drawable.icon_pause_menu);
            } else {
//                ivPlayOrPause.setTag(KEY_TAG_TO_PAUSE, false);
                isPlaying = false;
                ivPlayOrPause.setImageResource(R.drawable.icon_play_menu);
            }
        }
    }

    /**
     * 翻到句子所在的Page
     *
     * @param sentence
     * @return 如果当前句子所在的页免费则返回true，否则返回false
     */
    public boolean turnPageOfSentence(Sentence sentence) {
        int leftPage = 0;
        int rightPage = 0;
        int pageNo = sentence.pageNo;

        if (mLeftIndex < allPages.size()) {
            leftPage = allPages.get(mLeftIndex).pageNo;
        }
        if (mRightIndex < allPages.size()) {
            rightPage = allPages.get(mRightIndex).pageNo;
        }

        if (pageNo == leftPage || pageNo == rightPage) {  // 不需要翻页
            if (!mPurchased) {
                if (!checkSentenceFree(leftPage) || !checkSentenceFree(rightPage)) {
                    boolean supportUnlock = getLockState();
                    if (supportUnlock) {
                        showUnlockTape(true);
                    }
                }
                if (checkSentenceFree(pageNo)) {
                    return true;
                } else {
                    showPlayOrPause(false);
                    cancelSentence();
                    showPayDialog(true);
                    return false;
                }
            } else {
                return true;
            }
        } else {
            cancelSentence();
            if (pageNo < leftPage) {  // 前翻
                showAnim(false);
                return false;

            } else if (pageNo > rightPage) {
                if (!mPurchased && mRightIndex + 1 >= mPayStartIndex) {
                    if (playIsAuto) {
                        showPlayOrPause(false);
                        cancelSentence();
                        if (getLockState()) {
                            showAnim(true);
                        } else {
                            showPayDialog(true);
                        }
                    }
                } else {
                    if (playIsAuto) {
                        showAnim(true);
                    }
                }
                return false;
            }
            return false;
        }
    }

    /**
     * 翻到句子所在的Page
     *
     * @param sentence
     * @return 如果当前句子所在的页免费则返回true，否则返回false
     */
    public boolean turnPageOfSentence2(Sentence sentence) {
        int leftPage = 0;
        int rightPage = 0;
        int pageNo = sentence.pageNo;

        if (mLeftIndex < allPages.size()) {
            leftPage = allPages.get(mLeftIndex).pageNo;
        }
        if (mRightIndex < allPages.size()) {
            rightPage = allPages.get(mRightIndex).pageNo;
        }
        if (pageNo == leftPage || pageNo == rightPage) {  // 不需要翻页
            if (!mPurchased) {
                if (checkSentenceFree(pageNo)) {
                    return true;
                } else {
                    showPlayOrPause(false);
                    cancelSentence();
                    return false;
                }
            } else {
                return true;
            }
        } else {
            cancelSentence();
            if (pageNo < leftPage) {  // 前翻
                showAnim(false);
                return false;
            } else if (pageNo > rightPage) {
                if (!mPurchased && mRightIndex + 1 >= mPayStartIndex) {
                    showPlayOrPause(false);
                    cancelSentence();
                } else {
                    if (playIsAuto) {
                        showAnim(true);
                    }
                }
                return false;
            }
            return false;
        }
    }

    /***
     * 判断当前页是否免费
     * @param pageNo
     * @return
     */
    private boolean checkSentenceFree(int pageNo) {
        if (mPurchased) return true;
        int beginPageNum = allLessons.get(mBookDetail.freeLessons).beginPage;
        if (pageNo < beginPageNum) return true;
        else return false;
    }

    private void onSentenceBegin(Sentence sentence) {
        updateTranslation(sentence);
        renderReadingAreaHint(sentence.sentenceId);
    }

    /**
     * 更新中文翻译
     *
     * @param sentence
     */
    public void updateTranslation(Sentence sentence) {
        if (sentence != null && !TextUtils.isEmpty(sentence.displayCn))
            if (tvCnText != null)
                tvCnText.setText(sentence.displayCn);
    }

    /**
     * 绘制可读区域
     */
    private void renderTouchArea() {
        if (mBookHandler == null) {
            mBookHandler = new BookHandler(this);
        }
        removeTouchArea();
        mBookHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (leftFinish && rightFinish) {
                    if (allPages == null || allPages.size() == 0) return;
                    touchAreas.clear();
                    setTouchView(allPages.get(mLeftIndex).sentences, touchAreas, true);
                    setTouchView(allPages.get(mRightIndex).sentences, touchAreas, false);
                    mBookHandler.removeCallbacks(this);
                    mBookHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            playOrPauseSentence(true);
                        }
                    }, 100);
                } else {
                    renderTouchArea();
                }
            }
        }, 100);
        return;
    }

    /**
     * 绘制左侧点读框
     */
    private void renderTouchAreaLeft() {
        if (mBookHandler == null) {
            mBookHandler = new BookHandler(this);
        }
        removeTouchArea();
        mBookHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (leftFinish) {
                    if (allPages == null || allPages.size() == 0) return;
                    touchAreas.clear();
                    setTouchView(allPages.get(mLeftIndex).sentences, touchAreas, true);
                    mBookHandler.removeCallbacks(this);
                    mBookHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            playOrPauseSentence(true);
                        }
                    }, 100);
                } else {
                    renderTouchAreaLeft();
                }
            }
        }, 100);
        return;
    }

    /**
     * 绘制透明点读区域
     *
     * @param sentenceList
     * @param touchAreas
     */
    private void setTouchView(List<Sentence> sentenceList, SparseArray<View> touchAreas, boolean isLeft) {
        if (flFirst == null || flSecond == null) return;
        if (sentenceList == null || sentenceList.isEmpty()) {
            return;
        }
        // render touch area
        if (ratio_h < 0 || ratio_w < 0) {
            return;
        }
        for (int i = 0; i < sentenceList.size(); i++) {
            final Sentence sentence = sentenceList.get(i);
            float widthTouchArea = (Float.valueOf(sentence.endX) - Float.valueOf(sentence.startX)) * ratio_w;
            float heightTouchArea = (Float.valueOf(sentence.endY) - Float.valueOf(sentence.startY)) * ratio_w;
            float topMargin = Float.valueOf(sentence.startY) * ratio_h;
            float leftMargin = Float.valueOf(sentence.startX) * ratio_w;
            if (widthTouchArea > 0 && heightTouchArea > 0) {
                FrameLayout.LayoutParams layoutParams =
                        new FrameLayout.LayoutParams((int) widthTouchArea, (int) heightTouchArea);
                layoutParams.topMargin = (int) topMargin;
                layoutParams.leftMargin = (int) leftMargin;

                AudioSentenceView imageView = new AudioSentenceView(this);
                imageView.setStartX(Float.valueOf(sentence.startX) * ratio_w);
                imageView.setStartY(Float.valueOf(sentence.startY) * ratio_h);
                imageView.setEndX(Float.valueOf(sentence.endX) * ratio_w);
                imageView.setEndY(Float.valueOf(sentence.endY) * ratio_h);
                imageView.setTag(sentence);
                imageView.setLayoutParams(layoutParams);
//                imageView.setBackgroundColor(getResources().getColor(R.color.black));
                imageView.setOnClickListener(mSentenceClickListener);
                if (isLeft) {
                    flFirst.addView(imageView);
                } else {
                    flSecond.addView(imageView);
                }
                touchAreas.put(sentence.sentenceId, imageView);
            }
        }
    }

    private View.OnClickListener mSentenceClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Object o = v.getTag();
            if (o instanceof Sentence) {
                Sentence s = (Sentence) o;
                if (!checkSentenceFree(s.pageNo)) {
                    showPayDialog(true);
                }
                cancelSentence();
                readSentence(s);
            }
        }
    };

    /**
     * 移除可播放view
     */
    private void removeTouchArea() {
        if (flFirst != null) {
            int childCount = flFirst.getChildCount();
            for (int i = 0; i < childCount; i++) {
                View childView = flFirst.getChildAt(i);
                if (childView != null && childView.getTag() != null) {
                    if (childView.getTag() instanceof Sentence) {
                        flFirst.removeView(childView);
                    }
                }
            }
            flFirst.removeAllViews();
        }
        if (flSecond != null) {
            int childCount = flSecond.getChildCount();
            for (int i = 0; i < childCount; i++) {
                View childView = flSecond.getChildAt(i);
                if (childView != null && childView.getTag() != null) {
                    if (childView.getTag() instanceof Sentence) {
                        flSecond.removeView(childView);
                    }
                }
            }
            flSecond.removeAllViews();
        }
    }

    /**
     * 当前正在读的句子提示[红色方框、放大提示]
     *
     * @param sentenceId
     */
    public void renderReadingAreaHint(int sentenceId) {
        if (touchAreas != null && touchAreas.size() != 0) {
            AudioSentenceView reading = (AudioSentenceView) touchAreas.get(sentenceId);
            if (reading == null) {
                return;
            }
            //TODO 1.正在播放的句子红色方框
            reading.setMaskDrawable(R.drawable.shape_scale_bg_radio_3);

            //TODO 2.正在播放的句子放大提示
            renderReadingAreaHint(reading);

        }
    }

    /**
     * 正在播放的句子放大提示
     *
     * @param reading
     */
    private void renderReadingAreaHint(View reading) {
        if (ivFirst == null || ivSecond == null) return;
        if (mLBitmap == null) {
            mLBitmap = ivFirst.getmBitmap();
        }
        if (mRBitmap == null) {
            mRBitmap = ivSecond.getmBitmap();
        }
        Sentence sentence = (Sentence) reading.getTag();
        int pageNo_1 = 0, pageNo_2 = 0;
        if (flFirst.getTag() != null) {
            pageNo_1 = (int) flFirst.getTag();
        }
        if (flSecond.getTag() != null) {
            pageNo_2 = (int) flSecond.getTag();
        }
        if (sentence.pageNo == pageNo_1) {
            mBitmap = mLBitmap;
        } else if (sentence.pageNo == pageNo_2) {
            mBitmap = mRBitmap;
        } else {
//            ToastUtil.showLongToast("该句子不在此页，请检查"); // 出现此提示，表示翻页可能较大
            return;
        }
        if (mBitmap == null) return;
        float widthTouchArea = (Float.valueOf(sentence.endX) - Float.valueOf(sentence.startX));
        float heightTouchArea = (Float.valueOf(sentence.endY) - Float.valueOf(sentence.startY));
        float leftMargin = Float.valueOf(sentence.startX);
        float rightMargin = mBitmap.getWidth() - Float.valueOf(sentence.endX);
        float topMargin = Float.valueOf(sentence.startY);
        float bottomMargin = mBitmap.getHeight() - Float.valueOf(sentence.endY);
        if (leftMargin >= 0 && topMargin >= 0 &&
                widthTouchArea > 0 && heightTouchArea > 0 &&
                leftMargin + widthTouchArea <= mBitmap.getWidth() &&
                topMargin + heightTouchArea <= mBitmap.getHeight()) {
            Bitmap dest = Bitmap.createBitmap(mBitmap, (int) leftMargin, (int) topMargin, (int) widthTouchArea, (int) heightTouchArea);
            AudioSentenceView imageView = (AudioSentenceView) reading;
            imageView.setBackground(new BitmapDrawable(dest));
//            //放大时将该View置于顶层
//            imageView.bringToFront();
            setMultipleX(mBitmap, widthTouchArea, leftMargin, rightMargin);
            setMultipleY(mBitmap, heightTouchArea, topMargin, bottomMargin);
            //开始放大动画
            imageView.setScaleX(multipleX);
            imageView.setScaleY(multipleY);
        }
    }

    /**
     * 句子播放完 恢复原状
     *
     * @param sentenceId
     */
    public void clearReadingAreaHint(int sentenceId) {
        final AudioSentenceView reading = (AudioSentenceView) touchAreas.get(sentenceId);
        if (reading == null) {
            return;
        }
        reading.setMaskDrawable(0);
        reading.setBackground(null);
        // TODO 2.将已放大的可点读区域恢复
        reading.setScaleY(1.0f);
        reading.setScaleX(1.0f);
        L.d("清除的sentence ：" + sentenceId);
    }

    /**
     * 设置X方向放大倍数
     *
     * @param bitmap
     * @param widthTouchArea
     * @param leftMargin
     * @param rightMargin
     */
    private void setMultipleX(Bitmap bitmap, float widthTouchArea, float leftMargin, float rightMargin) {
        float widthMagnify = widthTouchArea / 2.0f * defaultMultiple;
        float widthLeft = leftMargin + widthTouchArea / 2.0f;
        float widthRight = widthTouchArea / 2.0f * defaultMultiple +
                leftMargin + widthTouchArea / 2.0f;
        int bitmapWidth = bitmap.getWidth();

        if (widthMagnify >= widthLeft ||
                widthRight >= bitmapWidth) {//放大后左边框或右边框超出有效范围

            float min = Math.min(leftMargin, rightMargin);
            multipleX = (2 * min + widthTouchArea) / widthTouchArea;
        } else if (widthTouchArea * multipleX > bitmapWidth) {
            multipleX = bitmap.getWidth() / widthTouchArea;
        } else {
            multipleX = defaultMultiple;
        }
    }

    /**
     * 设置Y方向放大倍数
     *
     * @param bitmap
     * @param heightTouchArea
     * @param topMargin
     * @param bottomMargin
     */
    private void setMultipleY(Bitmap bitmap, float heightTouchArea, float topMargin, float bottomMargin) {
        float heightMagnify = heightTouchArea / 2.0f * defaultMultiple;
        float heightTop = topMargin + heightTouchArea / 2.0f;
        float heightBottom = heightTouchArea / 2.0f * defaultMultiple +
                topMargin + heightTouchArea / 2.0f;
        int bitmapHeight = bitmap.getHeight();

        if (heightMagnify >= heightTop ||
                heightBottom >= bitmapHeight) {//放大后上边框或下边框超出有效范围

            float min = Math.min(topMargin, bottomMargin);
            multipleY = (2 * min + heightTouchArea) / heightTouchArea;
        } else if (heightTouchArea * multipleY > bitmapHeight) {
            multipleY = bitmap.getHeight() / heightTouchArea;
        } else {
            multipleY = defaultMultiple;
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            onBackPressed();
        } else if (id == R.id.iv_catalog) {
            if (mBookDetail == null) return;
            cancelSentence();
            showPlayOrPause(false);
            showCurCatalog(mCurPlayLessonIndex);
        } else if (id == R.id.iv_play_or_pause) {
            if (mBookDetail == null || !leftFinish || !rightFinish) return;
            showPlayOrPause();
        } else if (id == R.id.iv_setting) {
            if (mBookDetail == null) return;
            showMenu(true);
            cancelSentence();
            showPlayOrPause(false);
        } else if (id == R.id.iv_go_left) {
            if (!isFastClick())
                flipPage(false);
        } else if (id == R.id.iv_go_right) {
            if (!isFastClick())
                flipPage(true);
        } else if (id == R.id.iv_unlock_tape) {
            showPayDialog(true);
        }
    }

    private void showPlayOrPause() {
        if (isPlaying) {
            cancelSentence();
            showPlayOrPause(false);
        } else {
            if (rlUnlockTape.getVisibility() == View.VISIBLE) {
                showPayDialog(true);
            } else {
                playOrPauseSentence(true);
            }
        }
    }

    private void showCurCatalog(int mCurPlayLessonIndex) {
        if (mCatalogAdapter != null) {
            if (mPurchased || directUnlock()) {
                mCatalogAdapter.setPurchased(true);
            } else {
                mCatalogAdapter.setPurchased(false);
            }
            mCatalogAdapter.setCurPosition(mCurPlayLessonIndex);
            rvCatalog.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(Lessons lessons, int position) {
        if (!mPurchased && position >= mBookDetail.freeLessons) {
            boolean supportUnlock = getLockState();
            if (supportUnlock) {
                showUnlockTape(true);
                if (mCurPlayLessonIndex == position) {
                    showPlayOrPause(true);
                    playOrPauseSentence(true);
                } else {
                    cancelSentence();
                    showPlayOrPause(true);
                    changeLessons(allLessons.get(position));
                }
            } else {
                showPlayOrPause(false);
                playOrPauseSentence(false); // 暂停播放
                showPayDialog(true);
            }
        } else {
            if (mCurPlayLessonIndex == position) {
                showPlayOrPause(true);
                playOrPauseSentence(true);
            } else {
                cancelSentence();
                showPlayOrPause(true);
                changeLessons(allLessons.get(position));
            }
        }
        mSelectIndex = position;
        showCateLog(false);
    }

    /**
     * 是否显示锁状态
     *
     * @return
     */
    private boolean getLockState() {
        UserData userData = UserManager.getInstance().getUser();
        if (userData == null || !userData.baiduerVip) return true;
        if (userData.vipUnlockTextbookTimes == 0) return true;
        return false;
    }

    /**
     * 是否可以直接解锁
     *
     * @return
     */
    private boolean directUnlock() {
        UserData userData = UserManager.getInstance().getUser();
        if (userData == null || !userData.baiduerVip) return false;
        if (userData.vipUnlockTextbookTimes > userData.vipUnlockWarnTimes) return true;
        return false;
    }

    /**
     * 显示目录
     *
     * @param isShow
     */
    private void showCateLog(boolean isShow) {
        Animation mAnim;
        if (!isShow) {
            mAnim = AnimationUtils.loadAnimation(this, R.anim.dialog_bottom_out);
            rvCatalog.startAnimation(mAnim);
            rvCatalog.setVisibility(View.GONE);
        } else {
            mAnim = AnimationUtils.loadAnimation(this, R.anim.dialog_bottom_in);
            rvCatalog.startAnimation(mAnim);
            rvCatalog.getAdapter().notifyDataSetChanged();
            rvCatalog.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 显示解锁标记图
     *
     * @param show
     */
    public void showUnlockTape(boolean show) {
        if (rlUnlockTape != null) {
            if (show) rlUnlockTape.setVisibility(View.VISIBLE);
            else rlUnlockTape.setVisibility(View.GONE);
        }
    }

    private void showMenu(boolean isShow) {
        Animation mAnim;
        if (!isShow) {
            mAnim = AnimationUtils.loadAnimation(this, R.anim.dialog_bottom_out);
            rlMenu.startAnimation(mAnim);
            rlMenu.setVisibility(View.GONE);
        } else {
            mAnim = AnimationUtils.loadAnimation(this, R.anim.dialog_bottom_in);
            rlMenu.startAnimation(mAnim);
            rlMenu.setVisibility(View.VISIBLE);
        }
    }

    /*************************************** 支付业务 ******************************************/

    /**
     * 解锁弹窗
     *
     * @param isShow
     */
    private void showPayDialog(boolean isShow) {
        UserData userData = UserManager.getInstance().getUser();
        if (userData == null) return;
        if (isShow) {
            if (providerClickMode.equals("7")) {//水墨屏没有会员解锁,只有单本购买
                showBuyDialog();
            }
        } else {
            if (mBuyDialog != null) {
                mBuyDialog.dismiss();
            }
        }
    }

    /**
     * 单本购买
     */
    private void showBuyDialog() {
        if (mBuyDialog == null) {
            mBuyDialog = new PayDialog();
        }
        if (mBuyDialog.isShowing()) {
            return;
        }
        if (isFinishing() || isDestroyed()) return;
        mBuyDialog.show(this, new PayDialog.PayDialogListener() {
            @Override
            public void onGetNameView(TextView mBookName) {
                mBookName.setText(mBookDetail.bookName);
            }

            @Override
            public void onGetValidView(TextView mValidity) {
                mValidity.setText("购买后可获得全本  "+mProductionDetail.getProductionList().get(0).getValidityDays()+"有效期");
            }

            @Override
            public void onGetAmountView(TextView mAmount) {
                mAmount.setText("￥"+mProductionDetail.getProductionList().get(0).getFirstPrice());
            }

            @Override
            public void onGetConfirmBtn(TextView confirm) {
                confirm.setText("购买");
                confirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mBuyDialog.dismiss();
                        showProgress("正在打开支付页面");
                    }
                });
            }

            @Override
            public void onGetCancelBtn(TextView cancel) {
                cancel.setText("取消");
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mBuyDialog.dismiss();

                    }
                });

            }
        });
        mBuyDialog.setCanceledOnTouchOutside(true);
    }

    /**
     * 显示解锁成功弹窗
     */
    private void unlockSuccessDialog() {
        mPurchased = true;
        showPayDialog(false);
        showCateLog(false);
        showUnlockTape(false);
    }

    /*************************************** 支付业务 ******************************************/


    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {

            if (!(event.getX() > rlCatalog.getLeft() && event.getX() < rlCatalog.getRight() && event.getY() > rlCatalog.getTop() && event.getY() < rlCatalog.getBottom())) {
                if (rvCatalog.getVisibility() == View.VISIBLE) {
                    showCateLog(false);
                    return true;
                }
            }
            if (!(event.getX() > rlMenu.getLeft() && event.getX() < rlMenu.getRight() && event.getY() > rlMenu.getTop() && event.getY() < rlMenu.getBottom())) {
                if (rlMenu.getVisibility() == View.VISIBLE) {
                    showMenu(false);
                    return true;
                }
            }
            return super.dispatchTouchEvent(event);
        }
        return super.dispatchTouchEvent(event);
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        cancelSentence();
        showPlayOrPause(false);
        pauseAudio();
        dismissProgressAll();
        L.d("onPause---------");
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        doUnbindService();
        Intent intent = new Intent(this, MediaPlayerService.class);
        stopService(intent);
        L.d("onDestroy---------");
        super.onDestroy();
    }
}
